package cn.suxiaoxiang.suwebverify.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 自动登录缓存管理（仅内存，重启失效）
 */
public class AutoLoginCache {
    // IP -> (玩家名 -> 上次登录时间戳)
    private static final Map<String, Map<String, Long>> cache = new HashMap<>();

    /**
     * 记录玩家登录
     */
    public static void recordLogin(String ip, String playerName) {
        ip = IpUtil.normalizeIp(ip);
        cache.computeIfAbsent(ip, k -> new HashMap<>()).put(playerName, System.currentTimeMillis());
       //System.out.println("[SuWebVerify][AutoLogin] 记录自动登录: IP=" + ip + ", 玩家=" + playerName + ", 时间戳=" + System.currentTimeMillis());
    }

    /**
     * 判断是否可自动登录
     */
    public static boolean canAutoLogin(String ip, String playerName, long durationMillis) {
        ip = IpUtil.normalizeIp(ip);
        Map<String, Long> playerMap = cache.get(ip);
        if (playerMap == null) {
            //System.out.println("[SuWebVerify][AutoLogin] IP=" + ip + " 没有缓存记录");
            return false;
        }
        Long lastLogin = playerMap.get(playerName);
        if (lastLogin == null) {
            //System.out.println("[SuWebVerify][AutoLogin] 玩家=" + playerName + " 在IP=" + ip + " 下没有缓存记录");
            return false;
        }
        boolean canAuto = System.currentTimeMillis() - lastLogin <= durationMillis;
        //System.out.println("[SuWebVerify][AutoLogin] 检查自动登录: IP=" + ip + ", 玩家=" + playerName + ", 上次登录=" + lastLogin + ", 当前时间=" + System.currentTimeMillis() + ", 有效期(ms)=" + durationMillis + ", 结果=" + canAuto);
        return canAuto;
    }
} 